package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.dp.mndataif003;

import com.alibaba.cirtus.ots.application.adapter.ability.model.features.CustomerAddressFeatures;
import com.alibaba.cirtus.ots.application.adapter.ability.model.features.CustomerSaleScopeFeatures;
import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.CustomerAddressSDO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.CustomerSDO;
import com.alibaba.cirtus.ots.application.adapter.ability.model.sdo.CustomerSaleScopeSDO;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSONObject;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByCodes2Request;
import com.epoch.app.bcorder.model.dto.BaselineGetOrganizationByCodes2Response;
import com.epoch.app.bcorder.model.dto.OrganizationSDO;
import com.epoch.app.bcorder.service.BaseDataService;
import com.epoch.app.otsapplicationadaptersdk.dp.DpDelivery;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @author wangyibing
 */

@Component
public class MnDataIf003SDOBuilderV2 {
    Log log = Log.getLogger(MnDataIf003SDOBuilderV2.class);
    @Resource
    private BaseDataService baseDataService;

    public CustomerSaleScopeSDO buildCustomerSaleScopeSDO(DpDelivery dpDelivery, Map<String, OrganizationSDO> organizationMapByCustomers) {
        if (!"11".equals(dpDelivery.getSpart())) {
            log.error("MnDataIf003SDOBuilderV2_buildCustomerSaleScopeSDO_error_scItemGroup_not_can_sync,货品组非常温的不支持同步,addressCode:{},spart:{}", dpDelivery.getKunn2(), dpDelivery.getSpart());
            return null;
        }
        CustomerSaleScopeSDO customerSaleScopeSDO = new CustomerSaleScopeSDO();

        if (!organizationMapByCustomers.containsKey(dpDelivery.getVkorg())) {
            log.error("销售组织映射不上,kunnr:{},vkorg:{}", dpDelivery.getKunnr(), dpDelivery.getVkorg());
            return null;
        }
        OrganizationSDO saleOrgSDO = organizationMapByCustomers.get(dpDelivery.getVkorg());
        String saleOrg = saleOrgSDO.getId();
        String business = saleOrgSDO.getParentId();
        customerSaleScopeSDO.setOrgSaleOrganizationCode(saleOrg);
        customerSaleScopeSDO.setOrgBussinessUnitCode(business);
        if (StringUtils.isNotBlank(dpDelivery.getVkbur()) && organizationMapByCustomers.containsKey(dpDelivery.getVkbur())) {
            OrganizationSDO channelSDO = organizationMapByCustomers.get(dpDelivery.getVkbur());
            String saleChannel = channelSDO.getId();
            customerSaleScopeSDO.setOrgSaleChannelCode(saleChannel);
        } else {
            if (StringUtils.isNotBlank(dpDelivery.getVkbur())) {
                log.error("20220718去掉检验__销售渠道映射不上,kunnr:{},vkbur:{}", dpDelivery.getKunnr(), dpDelivery.getVkbur());
                //return null;
            }
        }

        if (StringUtils.isNotBlank(dpDelivery.getVkgrp()) && organizationMapByCustomers.containsKey(dpDelivery.getVkgrp())) {
            OrganizationSDO departSDO = organizationMapByCustomers.get(dpDelivery.getVkgrp());
            String department = departSDO.getId();
            customerSaleScopeSDO.setOrgSaleDepartmentCode(department);
        } else {
            if (StringUtils.isNotBlank(dpDelivery.getVkgrp())) {
                log.error("20220718去掉检验__销售部门映射不上,kunnr:{},vkgrp:{}", dpDelivery.getKunnr(), dpDelivery.getVkgrp());
                //return null;
            }
        }
        // 客户编码、销售区域、货品组、渠道编码、客户组
        customerSaleScopeSDO.setCustomerCode(dpDelivery.getKunnr());
        customerSaleScopeSDO.setSalesArea(dpDelivery.getBzirk());
        customerSaleScopeSDO.setItemGroup(dpDelivery.getSpart());
        customerSaleScopeSDO.setChannelCode(dpDelivery.getVtweg());
        customerSaleScopeSDO.setGroup(dpDelivery.getKtokd());
        customerSaleScopeSDO.setCustomerGroup(dpDelivery.getKdgrp());
        if (StringUtils.isNotBlank(dpDelivery.getAufsd())) {
            customerSaleScopeSDO.setStatus(0);
        } else {
            customerSaleScopeSDO.setStatus(1);
        }

        // 12.20增加逻辑：客户送达方数据中：kunnr==kunn2，且客户账户组ktokd == Z002 ，状态标记-1
        if (dpDelivery.getKunnr().equals(dpDelivery.getKunn2()) && dpDelivery.getKtokd().equals("Z002")) {
            customerSaleScopeSDO.setStatus(-1);
        }

        OrganizationSDO departSDO = organizationMapByCustomers.get(dpDelivery.getVkgrp());
        OrganizationSDO channelSDO = organizationMapByCustomers.get(dpDelivery.getVkbur());
        // features
        CustomerSaleScopeFeatures customerSaleScopeFeatures = new CustomerSaleScopeFeatures();
        if (Objects.nonNull(departSDO) && Objects.nonNull(departSDO.getName())) {
            customerSaleScopeFeatures.setOutOrgSalesDepartmentName(departSDO.getName());
        }
        if (Objects.nonNull(channelSDO) && Objects.nonNull(channelSDO.getName())) {
            customerSaleScopeFeatures.setOutOrgSalesChannelName(channelSDO.getName());
        }

        customerSaleScopeFeatures.setTransportArea(dpDelivery.getLzone());
        customerSaleScopeFeatures.setOutOrgSalesChannelCode(dpDelivery.getVkbur());
        customerSaleScopeFeatures.setOutOrgSalesDepartmentCode(dpDelivery.getVkgrp());
        customerSaleScopeFeatures.setStoreHouse(dpDelivery.getVwerk());
        String scopeFeatures = JSONObject.toJSONString(customerSaleScopeFeatures);
        customerSaleScopeSDO.setFeatures(scopeFeatures);
        return customerSaleScopeSDO;
    }

    public CustomerAddressSDO buildCustomerAddressSDO(DpDelivery address, Map<String, OrganizationSDO> organizationMapByCustomers) {
        // 查重条件不可为空
        if (StringUtils.isBlank(address.getKunnr()) || StringUtils.isBlank(address.getVkorg()) || StringUtils.isBlank(address.getKunn2()) || StringUtils.isBlank(address.getSpart()) || StringUtils.isBlank(address.getVtweg())) {
            log.error("MnDataIf003SDOBuilderV2_buildCustomerAddressSDO_repeat,送达方唯一条件都不可为空,客户编码:{},地址编码:{},销售组织:{},货品组:{},业务渠道:{}", address.getKunnr(), address.getKunn2(), address.getVkorg(), address.getSpart(), address.getVtweg());
            return null;
        }
        if (!"11".equals(address.getSpart())) {
            log.error("MnDataIf003SDOBuilderV2_buildCustomerAddressSDO_error_scItemGroup_not_can_sync,货品组非常温的不支持同步,addressCode:{},spart:{}", address.getKunn2(), address.getSpart());
            return null;
        }
        // 字段映射
        CustomerAddressSDO customerAddressSDO = new CustomerAddressSDO();
        if (!organizationMapByCustomers.containsKey(address.getVkorg())) {
            log.error("销售组织映射不上,kunnr:{},vkorg:{}", address.getKunnr(), address.getVkorg());
            return null;
        }
        OrganizationSDO saleOrgSDO = organizationMapByCustomers.get(address.getVkorg());
        String saleOrg = saleOrgSDO.getId();
        String business = saleOrgSDO.getParentId();
        customerAddressSDO.setOrgSaleOrganizationCode(saleOrg);
        customerAddressSDO.setOrgBussinessUnitCode(business);

        if (StringUtils.isNotBlank(address.getVkbur()) && organizationMapByCustomers.containsKey(address.getVkbur())) {
            OrganizationSDO channelSDO = organizationMapByCustomers.get(address.getVkbur());
            String saleChannel = channelSDO.getId();
            customerAddressSDO.setOrgSaleChannelCode(saleChannel);
        } else {
            if (StringUtils.isNotBlank(address.getVkbur())) {
                log.error("20220718去掉检验__销售渠道映射不上,kunnr:{},vkbur:{}", address.getKunnr(), address.getVkbur());
                //return null;
            }
        }

        if (StringUtils.isNotBlank(address.getVkgrp()) && organizationMapByCustomers.containsKey(address.getVkgrp())) {
            OrganizationSDO departSDO = organizationMapByCustomers.get(address.getVkgrp());
            String department = departSDO.getId();
            customerAddressSDO.setOrgSaleDepartmentCode(department);
        } else {
            if (StringUtils.isNotBlank(address.getVkgrp())) {
                log.error("20220718去掉检验__销售部门映射不上,kunnr:{},vkgrp:{}", address.getKunnr(), address.getVkgrp());
                //return null;
            }
        }
        customerAddressSDO.setAddressName(address.getName1());
        customerAddressSDO.setCustomerAccountGroup(address.getKtokd());
        customerAddressSDO.setCustomerCode(address.getKunnr());
        customerAddressSDO.setOutCustomerCode(address.getKunnr());
        customerAddressSDO.setContactName(address.getName());
        customerAddressSDO.setCellphoneNumber(address.getTelf1());
        customerAddressSDO.setAddress(address.getStras());
        customerAddressSDO.setSalesArea(address.getBzirk());
        customerAddressSDO.setAddressCode(address.getKunn2());
        customerAddressSDO.setOutCode(address.getKunn2());
        customerAddressSDO.setChannelCode(address.getVtweg());
        customerAddressSDO.setItemGroup(address.getSpart());
        if ("Z001".equals(address.getKtokd())) {
            customerAddressSDO.setType(1);
        } else {
            customerAddressSDO.setType(2);
        }

        if (StringUtils.isNotBlank(address.getAufsd())) {
            customerAddressSDO.setStatus(0);
        } else {
            customerAddressSDO.setStatus(1);
        }

        // 12.20增加逻辑：客户送达方数据中：kunnr==kunn2，且客户账户账户组ktokd == Z002 ，状态标记-1
        if (address.getKunnr().equals(address.getKunn2()) && "Z002".equals(address.getKtokd())) {
            customerAddressSDO.setStatus(-1);
        }
        CustomerAddressFeatures customerAddressFeatures = new CustomerAddressFeatures();
        customerAddressFeatures.setCustomerGroup(address.getKdgrp());
        customerAddressFeatures.setShippingConditions(address.getVsbed());
        customerAddressFeatures.setStoreHouse(address.getVwerk());
        customerAddressFeatures.setTransportAreaName(address.getLzone());
        customerAddressFeatures.setRegio(address.getRegio());
        customerAddressFeatures.setParvw(address.getParvw());
        customerAddressFeatures.setFrozenStatus(address.getAufsd());
        customerAddressFeatures.setKtokd(address.getKtokd());
        customerAddressFeatures.setKunn2(address.getKunn2());
        customerAddressFeatures.setOutOrgSalesDepartmentCode(address.getVkgrp());
        customerAddressFeatures.setOutOrgSalesChannelCode(address.getVkbur());

        OrganizationSDO channelSDO = organizationMapByCustomers.get(address.getVkbur());
        OrganizationSDO departSDO = organizationMapByCustomers.get(address.getVkgrp());
        if (Objects.nonNull(departSDO) && Objects.nonNull(departSDO.getName())) {
            customerAddressFeatures.setOutOrgSalesDepartmentName(departSDO.getName());
        }
        if (Objects.nonNull(channelSDO) && Objects.nonNull(channelSDO.getName())) {
            customerAddressFeatures.setOutOrgSalesChannelName(channelSDO.getName());
        }
        String addressFeatures = JSONObject.toJSONString(customerAddressFeatures);
        customerAddressSDO.setFeatures(addressFeatures);
        return customerAddressSDO;
    }

    public CustomerSDO buildCustomerMainData(DpDelivery address, Map<String, OrganizationSDO> organizationMapByCustomers) {
        // 查重条件不可为空
        if (StringUtils.isBlank(address.getKunnr()) || StringUtils.isBlank(address.getVkorg()) || StringUtils.isBlank(address.getKunn2()) || StringUtils.isBlank(address.getSpart()) || StringUtils.isBlank(address.getVtweg())) {
            log.error("MnDataIf003SDOBuilderV2_buildCustomerMainData_repeat,送达方唯一条件都不可为空,客户编码:{},地址编码:{},销售组织:{},货品组:{},业务渠道:{}", address.getKunnr(), address.getKunn2(), address.getVkorg(), address.getSpart(), address.getVtweg());
            return null;
        }
        if (!"11".equals(address.getSpart())) {
            log.error("MnDataIf003SDOBuilderV2_buildCustomerMainData_error_scItemGroup_not_can_sync,货品组非常温的不支持同步,addressCode:{},spart:{}", address.getKunn2(), address.getSpart());
            return null;
        }
        if (!organizationMapByCustomers.containsKey(address.getVkorg())) {
            log.error("销售组织映射不上,kunnr:{},vkorg:{}", address.getKunnr(), address.getVkorg());
            return null;
        }
        if (StringUtils.isNotBlank(address.getVkbur()) && !organizationMapByCustomers.containsKey(address.getVkbur())) {
            log.error("20220718去掉检验__销售渠道映射不上,kunnr:{},vkbur:{}", address.getKunnr(), address.getVkbur());
            //return null;
        }
        if (StringUtils.isNotBlank(address.getVkgrp()) && !organizationMapByCustomers.containsKey(address.getVkgrp())) {
            log.error("20220718去掉检验__销售部门映射不上,kunnr:{},vkgrp:{}", address.getKunnr(), address.getVkgrp());
            //return null;
        }
        CustomerSDO customerSDO = new CustomerSDO();
        customerSDO.setCode(address.getKunnr());
        customerSDO.setOutCode(address.getKunnr());
        customerSDO.setName(address.getName1());
        if (StringUtils.isNotBlank(address.getAufsd())) {
            customerSDO.setStatus(0);
        } else {
            customerSDO.setStatus(1);
        }
        return customerSDO;
    }

    @Nullable
    public Map<String, OrganizationSDO> getOrganizationMapByAddresses(List<DpDelivery> dpDeliveries) {
        Set<String> vkOrgSet = dpDeliveries.stream().map(DpDelivery::getVkorg).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> vkBurSet = dpDeliveries.stream().map(DpDelivery::getVkbur).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> vkGrpSet = dpDeliveries.stream().map(DpDelivery::getVkgrp).filter(StringUtils::isNotBlank).collect(Collectors.toSet());
        Set<String> orgSet = Sets.newHashSet(vkOrgSet);
        orgSet.addAll(vkBurSet);
        orgSet.addAll(vkGrpSet);
        // 启用且使用内部编码
        BaselineGetOrganizationByCodes2Request byCodes2Request = BaselineGetOrganizationByCodes2Request.builder().ids(Lists.newArrayList(orgSet)).status(1).build();
        BaselineGetOrganizationByCodes2Response byCodes2Response = baseDataService.baselineGetOrganizationByCodes2(byCodes2Request);
        if (Objects.isNull(byCodes2Response) || CollectionUtils.isEmpty(byCodes2Response.getResult())) {
            return null;
        }
        return byCodes2Response.getResult().stream().collect(Collectors.toMap(OrganizationSDO::getCode, a -> a, (a, b) -> a));
    }

}
